GoF 23 种设计模式介绍

创建型(5种)

工厂相关的模式

简单工厂、工厂方法、抽象工厂,这三个工厂模式是面试和实际开发中最容易混淆的。我们这里举例进行澄清。假设你在做一个 UI 库,要创建按钮和文本框。有 Windows 和 Mac 两种风格。

1
2
3
4
// 产品
interface Button { void render(); }
class WinButton implements Button { ... }
class MacButton implements Button { ... }

实际使用本质就一句话:简单工厂管 “集中创建”,工厂方法管 “扩展创建”,抽象工厂管 “配套创建”。


简单工厂(Simple Factory):不是 GoF 23 种之一,但常用。它的本质是把散落在各处的创建代码,集中到一个地方。痛点也非常明显,加一个 Linux 按钮必须改 ButtonFactory,工厂中的 if-else 违反开闭原则。

1
2
3
4
5
6
7
8
9
10
11
// 工厂——所有创建逻辑集中在一个方法
class ButtonFactory {
static Button create(String os) {
if ("win".equals(os)) return new WinButton();
if ("mac".equals(os)) return new MacButton();
throw new IllegalArgumentException();
}
}

// 使用
Button btn = ButtonFactory.create("win");


工厂方法(Factory Method):GoF 创建型模式之一。加一个 Linux 按钮,只需要新建 LinuxButton + LinuxButtonFactory,旧代码一行不改,符合开闭原则。它和简单工厂的本质区别是,简单工厂在一个工厂类用 if-else 决定创建哪种产品,而工厂方法则是每种产品有自己专属的工厂类,靠多态决定使用哪个工厂。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 工厂——每个具体工厂只负责一种产品
interface ButtonFactory {
Button create();
}
class WinButtonFactory implements ButtonFactory {
public Button create() { return new WinButton(); }
}
class MacButtonFactory implements ButtonFactory {
public Button create() { return new MacButton(); }
}

// 使用
ButtonFactory factory = new WinButtonFactory();
Button btn = factory.create();


抽象工厂(Abstract Factory):GoF 创建型模式之一。解决产品家族问题。现在你不止要按钮,还要文本框,而且它们必须风格一致(不能 Windows 按钮配 Mac 文本框)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 产品族
interface Button { void render(); }
interface TextBox { void render(); }
class WinButton implements Button { ... }
class MacButton implements Button { ... }
class WinTextBox implements TextBox { ... }
class MacTextBox implements TextBox { ... }

// 抽象工厂——生产一族产品
interface GUIFactory {
Button createButton();
TextBox createTextBox();
}

class WinFactory implements GUIFactory {
public Button createButton() { return new WinButton(); }
public TextBox createTextBox() { return new WinTextBox(); }
}

class MacFactory implements GUIFactory {
public Button createButton() { return new MacButton(); }
public TextBox createTextBox() { return new MacTextBox(); }
}

// 使用——整个应用只用同一个工厂
GUIFactory factory = new WinFactory();
Button btn = factory.createButton();
TextBox tb = factory.createTextBox();


单例模式

I - 简单饿汉式

优点是简单、线程安全(靠类加载机制)。缺点也非常明显,不管用不用,启动就创建。

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Logger {
// 类加载时就创建
private static final Logger INSTANCE = new Logger();
private Logger() {}

public static Logger getInstance() {
return INSTANCE;
}

public void log(String msg) {
System.out.println(msg);
}
}


II - 枚举饿汉式(用于极端安全的框架或基础设施)

线程安全,JVM 保证枚举实例全局唯一,连反射都干不掉它。但是不够面向对象,也不能懒加载。

1
2
3
4
5
6
7
8
9
10
public enum Logger {
INSTANCE;

public void log(String msg) {
System.out.println(msg);
}
}

// 使用
Logger.INSTANCE.log("hello");


III - 双重检查锁(DCL,推荐之一)

优点是线程安全、延迟加载,并且只在第一次创建时加锁,后面直接返回。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Logger {
private static volatile Logger instance;
private Logger() {}

public static Logger getInstance() {
if (instance == null) {
synchronized (Logger.class) {
if (instance == null) {
instance = new Logger();
}
}
}
return instance;
}
}


IV - 静态内部类(99% 场景强烈推荐)

利用 JVM 对静态内部类的延迟加载(Holder 类用到才加载)。线程安全、无锁、实现简洁。

1
2
3
4
5
6
7
8
9
10
11
public class Logger {
private Logger() {}

private static class Holder {
static final Logger INSTANCE = new Logger();
}

public static Logger getInstance() {
return Holder.INSTANCE;
}
}


建造者模式

为什么需要建造者?假设你要创建一个 Computer 对象:

1
2
3
4
5
6
7
class Computer {
String cpu;
String ram;
String disk;
String gpu;
String keyboard;
}

如果用构造方法:

1
Computer c = new Computer("i9", "32G", "1T SSD", "RTX4090", "机械键盘");

问题是:参数多难记,构造方法以后加一个参数所有调用方全炸。那么构建者模式是怎么解决的呢?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Computer {
// 必选
String cpu;
String ram;
// 可选
String disk;
String gpu;
String keyboard;

// 构造方法私有,外面不能直接 new
private Computer(Builder builder) {
this.cpu = builder.cpu;
this.ram = builder.ram;
this.disk = builder.disk;
this.gpu = builder.gpu;
this.keyboard = builder.keyboard;
}

// 建造者
static class Builder {
String cpu; // 必选
String ram; // 必选
String disk; // 可选
String gpu; // 可选
String keyboard; // 可选

// 必选参数放构造方法
Builder(String cpu, String ram) {
this.cpu = cpu;
this.ram = ram;
}

Builder disk(String disk) {
this.disk = disk;
return this; // 返回 this,支持链式调用
}

Builder gpu(String gpu) {
this.gpu = gpu;
return this;
}

Builder keyboard(String keyboard) {
this.keyboard = keyboard;
return this;
}

Computer build() {
return new Computer(this);
}
}
}

使用时:

1
2
3
4
5
Computer c = new Computer.Builder("i9", "32G")
.disk("1T SSD")
.gpu("RTX4090")
.keyboard("机械键盘")
.build();

建造者 = 链式调用 + 把”怎么组装”和”组装成什么”分开。构造方法参数超过 4 个,就该考虑它了。


原型模式

为什么需要原型模式呢?假设你有一个配置对象,里面嵌套了很多数据:

1
2
3
4
5
6
class Config {
String host;
int port;
String[] whitelist;
// 还有很多字段...
}

你想创建 10 个类似的配置,只是改一两个字段:

1
2
3
4
5
6
7
8
9
10
11
// ❎ 不用原型:每次都 new,手动一个个赋值
Config c1 = new Config();
c1.host = "192.168.1.1";
c1.port = 8080;
c1.whitelist = new String[]{"ip1", "ip2"};

Config c2 = new Config();
c2.host = "192.168.1.2"; // 只改这一个
c2.port = 8080; // 其余一模一样
c2.whitelist = new String[]{"ip1", "ip2"};
// ... 重复到 c10

问题是:创建成本高(可能需要多次从数据库加载参数),写了一堆重复的赋值代码,并且调用方需要知道对象内部细节,不符合封装原则。原型模式怎么解决?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 实现 Cloneable 接口,标记"我可以克隆"
class Config implements Cloneable {
String host;
int port;
String[] whitelist;

// 构造方法:模拟"创建成本高"
Config() {
// 假设这里要从数据库加载一堆默认值
this.port = 8080;
this.whitelist = new String[]{"ip1", "ip2"};
}

// 克隆方法
@Override
protected Config clone() throws CloneNotSupportedException {
return (Config) super.clone(); // 浅拷贝
}

@Override
public String toString() {
return host + ":" + port + " | " + Arrays.toString(whitelist);
}
}

使用时:

1
2
3
4
5
6
7
8
9
10
11
12
Config prototype = new Config();          // 创建原型(只创建一次)
prototype.host = "192.168.1.1";

Config c2 = prototype.clone(); // 复制一份
c2.host = "192.168.1.2"; // 只改要改的

Config c3 = prototype.clone();
c3.host = "192.168.1.3";

System.out.println(prototype); // 192.168.1.1:8080 | [ip1, ip2]
System.out.println(c2); // 192.168.1.2:8080 | [ip1, ip2]
System.out.println(c3); // 192.168.1.3:8080 | [ip1, ip2]

上面的 clone() 是浅拷贝——引用类型的字段(如 whitelist 数组)只是复制了引用,没有复制数组本身:

1
2
c2.whitelist[0] = "hacked";
System.out.println(prototype.whitelist[0]); // 输出 "hacked"!原对象被改了

需要深拷贝时,手动复制引用字段:

1
2
3
4
5
6
@Override
protected Config clone() throws CloneNotSupportedException {
Config cloned = (Config) super.clone();
cloned.whitelist = this.whitelist.clone(); // 数组也复制一份
return cloned;
}

在 Spring 里,Bean 默认是 Singleton,但你可以把 scope 设为 prototype——每次注入都给你一个新对象。这就是原型模式的应用。

原型模式 = “以现有对象为模板,复制一份出来改改”。适合创建成本高、但彼此差异小的对象。注意浅拷贝的坑。


结构型(7 种)ABCD FFP

下面们我用统一的一个场景:咖啡店点单系统,把 7 个结构型模式全部串起来讲。


适配器A - 接口的转换

场景:店里有一台老式咖啡机,只有酿制咖啡的 brewCoffee() 方法。但新系统要求所有饮品都实现 makeDrink() 接口。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 新系统接口
interface DrinkMaker {
void makeDrink();
}

// 老式咖啡机(接口不兼容)
class OldCoffeeMachine {
void brewCoffee() {
System.out.println("煮咖啡");
}
}

// 适配器
class CoffeeAdapter implements DrinkMaker {
OldCoffeeMachine machine;

CoffeeAdapter(OldCoffeeMachine machine) {
this.machine = machine;
}

public void makeDrink() {
machine.brewCoffee(); // 转接
}
}

本质上:适配器 = 接口翻译机。两个东西功能已经能配合,只是接口对不上。


桥接B - 抽象和实现分离

场景:咖啡有种类(美式、拿铁),也有尺寸(中杯、大杯)。

如果写死继承:AmericanLargeCoffee、AmericanMediumCoffee;LatteLargeCoffee、LatteMediumCoffee。那么会有类爆炸的问题。桥接的实现是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// 实现维度
interface Size {
void cupSize();
}

class Medium implements Size {
public void cupSize() { System.out.println("中杯"); }
}

class Large implements Size {
public void cupSize() { System.out.println("大杯"); }
}

// 抽象维度
abstract class Coffee {
protected Size size;

Coffee(Size size) {
this.size = size;
}

abstract void make();
}

class Americano extends Coffee {
Americano(Size size) { super(size); }

void make() {
System.out.print("美式 ");
size.cupSize();
}
}

本质上:桥接 = 两个变化方向,各自独立发展。抽象不关心实现,实现不关心抽象。


组合C - 树形结构统一处理

场景:咖啡店有单品咖啡,也有套餐(套餐里还能套套餐)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
interface MenuItem {
int cost();
}

class Coffee implements MenuItem { // Coffee 单品咖啡
public int cost() { return 15; }
}

class Combo implements MenuItem { // Combo 套餐
List<MenuItem> items = new ArrayList<>();

void add(MenuItem item) {
items.add(item);
}

public int cost() {
int total = 0;
for (MenuItem item : items) {
total += item.cost();
}
return total;
}
}

组合的本质是:把 “单个对象” 和 “对象容器” 当成同一种东西处理。


装饰器D - 动态加功能

场景:咖啡基础价 15 元,加奶 +3,加糖 +1。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
interface Coffee {
int cost();
}

class SimpleCoffee implements Coffee {
public int cost() { return 15; }
}

abstract class CoffeeDecorator implements Coffee {
protected Coffee coffee;

CoffeeDecorator(Coffee coffee) {
this.coffee = coffee;
}
}

class MilkDecorator extends CoffeeDecorator {
MilkDecorator(Coffee coffee) { super(coffee); }

public int cost() {
return coffee.cost() + 3;
}
}

class SugarDecorator extends CoffeeDecorator {
SugarDecorator(Coffee coffee) { super(coffee); }

public int cost() {
return coffee.cost() + 1;
}
}

使用时:

1
2
Coffee c = new MilkDecorator(new SugarDecorator(new SimpleCoffee()));
System.out.println(c.cost()); // 19

本质上:装饰器是在不改原对象基础上,套一层加一层功能。

装饰器是 is-a 形式,对外表现还是同一个接口;组合是 has-a 形式,对外表现是树形结构。


外观模式F - 统一的入口

场景:点一杯咖啡,后台要:

  • 磨豆
  • 烧水
  • 冲泡
  • 清洗
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Grinder { void grind() {} }  // 研磨机
class Boiler { void boil() {} } // 锅炉机
class Brewer { void brew() {} } // 酿造机
class Cleaner { void clean() {} } // 清洗机

// 外观
class CoffeeMachineFacate {
void makeCoffee() {
new Grinder().grind();
new Boiler().boil();
new Brewer().brew();
new Cleaner().clean();
}
}

本质上:外观 = 复杂系统的简化入口。客户只跟外观打交道,不关心内部子系统。

外观的目的是简化接口,把多个接口变为一个统一入口;而适配器的目的是转换接口,把一个旧接口转变为一个新的接口。


享元模式F - 共享对象

场景:咖啡店有 1000 个订单,每个订单都记录咖啡口味。口味种类有限(美式、拿铁),但订单很多。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class CoffeeType {
String name;
CoffeeType(String name) { this.name = name; }
}

class CoffeeFactory {
static Map<String, CoffeeType> map = new HashMap<>(); // Flywight

static CoffeeType get(String name) {
if (!map.containsKey(name)) {
map.put(name, new CoffeeType(name));
}
return map.get(name);
}
}

本质上,享元就是把 “可共享的部分” 抽出来复用,不重复创建。

享元模式的目的是减少重复对象的创建,相比于单例模式,它不保证对象 JVM 层面的全局唯一。


代理模式P - 引入代理切面

场景:比如加一层控制访问的代理。VIP 咖啡机很贵,只有管理员能直接用,其他人通过代理使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
interface CoffeeMachine {
void make();
}

class RealMachine implements CoffeeMachine {
public void make() {
System.out.println("制作咖啡");
}
}

class ProxyMachine implements CoffeeMachine {
RealMachine machine = new RealMachine();
boolean isAdmin;

ProxyMachine(boolean isAdmin) {
this.isAdmin = isAdmin;
}

public void make() {
if (isAdmin) {
machine.make();
} else {
System.out.println("无权限");
}
}
}

本质上:代理真正干的事是控制访问,它把权限校验、缓存逻辑、日志和监控等集中到一个地方(切面),让真实对象只管自己的核心逻辑,从而实现功能上的解耦。


行为型(11种)CC II MM o SS TV

责任链 C

一个请求,多个对象都可能处理,但谁处理不确定,而且处理顺序可能变化。没有责任链时,代码中会出现大量的 if-else,而责任链把 “谁处理 “这件事从调用方手里拿走,让处理者自己排好队,请求自己往前走。请求不知道谁会处理,处理者不知道请求从哪来,大家只认链条。

场景:咖啡店请假审批:店员 → 店长 → 区域经理,谁权限够谁批。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
abstract class Handler {
Handler next;
void setNext(Handler next) { this.next = next; }
abstract void handle(int days);
}

class Clerk extends Handler {
void handle(int days) {
if (days <= 1) System.out.println("店员批准");
else if (next != null) next.handle(days);
}
}

class Manager extends Handler {
void handle(int days) {
if (days <= 3) System.out.println("店长批准");
else if (next != null) next.handle(days);
}
}

class Regional extends Handler {
void handle(int days) {
System.out.println("区域经理批准");
}
}

最经典的责任链模式实现还包括 Servlet Filter、Spring MVC Interceptor、Spring Security 过滤器链、MyBatis 插件机制 (Interceptor)、Netty 管道 (ChannelPipeline) 等等,详细请参考 《设计模式之责任链》。

责任链的本质是把多个处理者串成一条线,请求自己往前走,直到有人接。


命令 C

场景:点单系统 - 下单、取消、重做。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
interface Command {
void execute();
void undo();
}

class OrderCommand implements Command {
Receiver receiver;
OrderCommand(Receiver r) { this.receiver = r; }
public void execute() { receiver.takeOrder(); }
public void undo() { receiver.cancelOrder(); }
}

class Receiver {
void takeOrder() { System.out.println("下单"); }
void cancelOrder() { System.out.println("取消"); }
}

没有命令模式时,调用方直接:

1
2
waiter.takeOrder();
chef.cook();
  • 想撤销一个订单?没法撤
  • 想把订单存起来、稍后执行?没法存
  • 想记录操作日志?散落各处

本质上 ,命令模式就是把 “下单” 这个动作封装成对象,它可以被存储、传递、撤销、重放。


解释器 I

场景:简单规则引擎:a AND b、a OR b。

1
2
3
4
5
6
7
8
9
10
11
interface Expression { // Interpreter 解释器
boolean interpret(Context c);
}

class AndExpression implements Expression {
Expression left, right;
AndExpression(Expression l, Expression r) { left = l; right = r; }
public boolean interpret(Context c) {
return left.interpret(c) && right.interpret(c);
}
}

没有解释器时,你写一堆 if-else 解析字符串规则:

1
2
if (rule.contains("AND")) { ... }
else if (rule.contains("OR")) { ... }

而解释器要做的,就是把”规则”变成”语法树”,每个节点自己知道怎么解释自己。

本质上,解释器就是定义一套语法规则,然后写代码去解释执行。

实际项目大多直接用现成引擎(SpEL、Groovy),手写解释器很少。


迭代器 I

场景:遍历菜单,不管它是数组还是链表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.Iterator;

public class ArrayMenu<E> implements Iterable<E> {

private final E[] items;
public ArrayMenu(E[] items) { this.items = items; }

@Override
public Iterator<E> iterator() {
return new Iterator<>() {
int pos = 0;

@Override
public boolean hasNext() {
return pos < items.length;
}

@Override
public E next() {
return items[pos++];
}
};
}
}

使用时:

1
2
3
4
5
6
7
public static void main(String[] args) {
String[] items = {"玛奇朵", "拿铁"};
ArrayMenu<String> menu = new ArrayMenu<>(items);
for (String item : menu) { // 👈🏻
System.out.println(item);
}
}

本质上,迭代器就是把 “怎么遍历” 从 “集合本身” 里抽出来,统一接口。


中介者 M

场景:服务员、厨师、收银员不直接互相喊,全通过对讲机。

1
2
3
4
5
6
7
8
9
10
11
12
interface Mediator {
void notify(Colleague sender, String event);
}

class CoffeeShopMediator implements Mediator {
Waiter waiter;
Chef chef;
public void notify(Colleague sender, String event) {
if (sender == waiter) chef.cook();
if (sender == chef) waiter.serve();
}
}

中介者就是把对象之间乱七八糟的网状调用,收拢到一个中心对象里。


备忘录 M

Originator 把自己的状态装进一个”只读黑盒”Memento 里,交给 Caretaker 保管;需要恢复时,Originator 从黑盒里取出状态写回自己。外部谁都看不到、改不了里面的内容。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 备忘录:存状态,对外只读。这就是"黑盒",拿到的人能看,但不能改。
class Memento {
private String state;
Memento(String s) { state = s; }
String getState() { return state; }
}

// 原发器:产生状态、创建备忘录、从备忘录恢复。状态的内部结构只有 Originator 知道,Memento 和 Caretaker 都不关心
class Originator {
String state;
Memento save() { return new Memento(state); }
void restore(Memento m) { state = m.getState(); }
}

// 管理者:只负责持有备忘录,它甚至不需要知道 Memento 里面有什么
class Caretaker {
Memento memento;
}

使用时:

1
2
3
4
5
6
7
8
9
Originator o = new Originator();
o.state = "咖啡机配置A";

Caretaker c = new Caretaker();
c.memento = o.save(); // 保存

o.state = "咖啡机配置B"; // 改了
o.restore(c.memento); // 恢复
System.out.println(o.state); // 输出 "咖啡机配置A"

备忘录模式解决的问题是:需要保存/恢复对象状态,但不想暴露内部细节。没有备忘录时:

1
2
3
// 直接暴露内部字段
String state = coffeeMachine.state; // 外部能随便改
coffeeMachine.state = state; // 破坏封装

痛点是暴露内部状态而破坏了封装,类一改,外部全炸。备忘录让对象自己负责保存/恢复,外部只拿到一个 “黑盒” 快照。

一句话概括备忘录,就是状态可以存,但怎么存的你别管。


观察者 o

场景:咖啡好了,通知所有顾客。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
interface Observer {
void handleEvent(String event);
}

class Customer implements Observer {
public void handleEvent(String event) {
System.out.println("收到通知事件:" + event);
}
}

class CoffeeMachine {
List<Observer> observers = new ArrayList<>();
void addObserver(Observer o) { observers.add(o); }
void notifyAll(String event) {
for (Observer o : observers) o.handleEvent(event);
}
}

使用时:

1
2
3
4
5
public static void main(String[] args) {
CoffeeMachine coffeeMachine = new CoffeeMachine();
coffeeMachine.addObserver(new Customer());
coffeeMachine.notifyAll("咖啡做好了!");
}

观察者模式解决的问题是一个对象变了,需要通知一群对象,但不知道具体是谁、有多少。在没有观察者的时候:

1
2
3
4
5
6
coffeeMachine.done() {
customer1.notify();
customer2.notify();
waiter.notify();
// 加一个新顾客?改这里
}

痛点是被通知者和通知者紧耦合、加新观察者要改原代码、通知逻辑散落在通知者内部,观察者让通知者只管 “我变了”,谁关心谁自己来注册。

观察者 = 一个变,一群跟着变。发布-订阅。发布者不认识订阅者,订阅者自己决定要不要订阅消息。


状态 S

场景:咖啡机有 待机 → 制作中 → 完成。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
interface State {
void handle(CoffeeMachine m);
}

class StandbyState implements State {
public void handle(CoffeeMachine m) {
System.out.println("开始制作");
m.setState(new BrewingState());
}
}

class BrewingState implements State {
public void handle(CoffeeMachine m) {
System.out.println("制作完成");
m.setState(new DoneState());
}
}

class CoffeeMachine {
State state;
void setState(State s) { state = s; }
void request() { state.handle(this); }
}

状态模式解决的问题:对象行为随状态变化,if-else/switch 堆到无法维护。没有状态时:

1
2
3
4
if (state == STANDBY) { ... }
else if (state == BREWING) { ... }
else if (state == DONE) { ... }
// 加一个"清洗中"状态?所有 if 都改

痛点:

  • 状态判断散落各处
  • 加状态 = 改所有 if
  • 状态之间可能非法跳转(待机直接跳完成?)

状态模式把每个状态封装成类,状态自己决定 “能做什么、做完跳到哪”。

一句话概括状态模式,就是它把 if-else 换成 “状态对象”,【状态自己管自己的行为,干完之后自己切换状态】。


策略 S

场景:支付方式 - 支付宝 / 微信 / 银行卡。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
interface PaymentStrategy {
void pay(int amount);
}

class AliPay implements PaymentStrategy {
public void pay(int amount) { System.out.println("支付宝付 " + amount); }
}

class WeChatPay implements PaymentStrategy {
public void pay(int amount) { System.out.println("微信付 " + amount); }
}

class Checkout {
PaymentStrategy strategy;
Checkout(PaymentStrategy s) { strategy = s; }
void pay(int amount) { strategy.pay(amount); }
}

策略模式解决的问题:同一件事有多种做法,需要运行时切换,不想写 if-else。没有策略时:

1
2
3
if ("支付宝".equals(type)) { ... }
else if ("微信".equals(type)) { ... }
else if ("银行卡".equals(type)) { ... }

痛点:

  • 加支付方式 = 改这个类
  • 算法和调用方紧耦合
  • 算法之间互相影响

本质上,策略模式就是把 “怎么干” 抽出来,随时换一种干法。策略把每种算法封装成类,调用方只认接口,运行时随便换。


模板 T

场景:做咖啡的固定流程:烧水 → 冲泡 → 倒杯。但美式和拿铁冲泡方式不同。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
abstract class CoffeeTemplate {
// 模板方法(final 防止子类改流程)
final void make() {
boilWater();
brew();
pour();
}

void boilWater() { System.out.println("烧水"); }
abstract void brew();
void pour() { System.out.println("倒杯"); }
}

class Americano extends CoffeeTemplate {
void brew() { System.out.println("滴滤冲泡"); }
}

模板方法的套路是,父类定方法执行流程、公用方法,子类只填变化的部分即可。它通常用于多个子类有相同流程,只有某些步骤不同,不想重复写流程代码的场景。


访问者 V

场景:咖啡店有多种商品(咖啡、甜点),现在要加一个 “计算卡路里” 的功能,但不想改商品类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Coffee implements Visitable {
public void accept(Visitor v) { v.visit(this); }
}

interface Visitable {
void accept(Visitor v);
}

interface Visitor {
void visit(Coffee c);
}

class CalorieVisitor implements Visitor {
public void visit(Coffee c) { System.out.println("咖啡 100 卡"); }
}

使用时:

1
2
3
4
public static void main(String[] args) {
Coffee coffee = new Coffee();
coffee.accept(new CalorieVisitor()); // 咖啡 100 卡
}

访问者模式通常用于一组类结构稳定,但经常需要加新操作,不想改这些类的场景。没有访问者时,加新功能:

1
2
3
4
5
6
class Coffee {
int calorie() { ... }
double price() { ... }
// 现在要加"打印标签"?改 Coffee 类
// 加"导出JSON"?再改 Coffee 类
}

痛点:类承担了太多非核心操作;加操作需要改类,违反开闭原则。访问者把操作抽出来,放到独立的 Visitor 类里,原类只管 “接受访问”。

访问者的本质是将操作从原数据中分抽离,增加新操作不改原类。